<?php
/**
 * Date: 16-12-8 上午11:11
 */

class DealService extends BaseService
{

    private static $self              =   NULL;
    private $mUser                    =   NULL;
    private $mUserFund                =   NULL;




    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }
        return self::$self;
    }


    public function __construct()
    {

        $this->mUser               =   new Involved_UserModel();
        $this->mUserFund           =   new Involved_UserFundModel();
    }

    /**
     * 资金增减操作
     */
    public function carry($userid,$amount,$eventid,$type,$changing,$detail,$note='')
    {

        // 用户当前资金 充值未投资资金/奖励资金/回款资金/再投资金
        $fund = $this->mUserFund->GetFund($userid);

        // 可变更资金字段
        $fundField = StatusEnum::fund_field();

        // 资金增减明细
        if (!is_array($changing) || !$changing)
        {
            return  '变更资金无明细';
        }

        // 交易类型检查
        if (!array_key_exists($type, StatusEnum::type()))
        {
            return '资金操作类型错误';
        }

        // 更新的资金
        $updateFunds = [];

        // 计算增减资金
        foreach ($changing as $key => $value)
        {
            if (!array_key_exists($key, $fundField))
            {
                return '变更资金字段错误';
            }

            if (!is_numeric($value))
            {
                return '变更金额错误' ;
            }
            $key = strtolower($key);

            $updateFunds[$key] = $fund->$key + $value;

        }
         foreach($fund as $k=>$v){
             $fund1[$k] = $v;
         }

        // 资产变更之前的资金
        $fundBefore = json_encode($fund1);
        // 资产变更后的资金
        $fundAfter  = json_encode(array_merge($fund1, $updateFunds));
        // 获取操作时间
        list($ntime, $msec) = explode('.', microtime(true));

        // 构建交易记录数据
        $record = [
            // 用户ID
            'user_id'  => $userid,
            // 事件ID
            'event_id' => $eventid,
            // 金额
            'amount'   => $amount,
            // 交易类型
            'type'     => $type,
            // 资金变化字段
            'changing' => json_encode($changing),
            // 业务说明
            'detail'   => $detail,
            // 备注
            'note'     => $note ?$note: '',
                // 精确时间
                'add_msec' => $msec,
                // 添加时间
                'add_time' => $ntime,
                // 更新之前资金
                'update_before' => $fundBefore,
                // 更新之前资金
                'update_after'  => $fundAfter,
                ];


        $result =DB::table('user_fund')->where('user_id',$userid)->update($updateFunds);
        if ($result)
        {
            DB::table('deal_record')->insert($record);
            return 200;
        }
        return 'ERR';
    }


}




